package b3.scene.home
{
	import as3isolib.core.*;
	import as3isolib.display.*;
	import as3isolib.display.primitive.*;
	import as3isolib.display.renderers.*;
	import as3isolib.display.scene.*;
	import as3isolib.geom.*;
	import as3isolib.graphics.*;
	
	import b3.config.*;
	import b3.model.*;
	import b3.net.*;
	import b3.scene.*;
	import b3.scene.home.grid.*;
	import b3.util.*;
	import b3.widget.*;
	import b3.widget.basic.*;
	import b3.widget.card.CardItem;
	import b3.widget.home.bottom.*;
	import b3.widget.home.operation.*;
	import b3.widget.home.town.*;
	import b3.widget.home.unlock.UnlockSectionMovie;
	
	import com.greensock.*;
	import com.greensock.easing.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.Point;
	import flash.text.*;

	public class Town extends Sprite
	{
		public var isoScene:IsoScene;
		public var isoView:IsoView;

		public static const gridWidth:int = 64;
		public static const hoverHeight:Number = 0;
		private var highlight:HighlightGrid;
		private var lockGrids:IsoSprite;
		
		private var mouseDownPos:Pt;
		private var currentViewCenter:Pt;
		private var mouseDownViewCenter:Pt;
		
		private var currentBuildingIndex:int;
		private var mouseBuildingGrid:BuildingGrid;
		
		public var owner:Player;
		private var currentSection:int;
		
		private var replaceBuildings:Array;
		
		public function Town(owner:Player)
		{
			super();
			this.owner = owner;
			currentSection = 0;
			//场景               
			isoScene = new IsoScene();                        
			isoScene.hostContainer = this;
//			//坐标
//			var coordinate:CoordinateGrid = new CoordinateGrid();
//			coordinate.cellSize = gridWidth;
//			coordinate.setGridSize(60, 60, 2.2);
//			coordinate.showOrigin = false;
//			isoScene.addChild(coordinate);
			//高亮
			highlight = new HighlightGrid();
			highlight.cellSize = gridWidth;
			highlight.setGridSize(60, 60, 2);
			highlight.showOrigin = false;
			// 区域锁
			lockGrids = new IsoSprite();
			isoScene.addChild(lockGrids);
			var townConfig:TownConfig = Config.townConfigs[owner.townModel.townIndex];
			//背景
			var LayerBgr:Class = ResourceHelper.getInstance().getClassByName(townConfig.layerBgrClass);
			var bgGrid:IsoSprite = new IsoSprite();
			bgGrid.setSize(gridWidth, gridWidth, 0.1);
			bgGrid.moveBy(0, 0, -2);
			isoScene.addChild(bgGrid);
			bgGrid.sprites = [LayerBgr]
			bgGrid.container.mouseEnabled = false;
			bgGrid.container.mouseChildren = false;
			//阴影
			var factory:as3isolib.core.ClassFactory = new as3isolib.core.ClassFactory(DefaultShadowRenderer);
			factory.properties = {shadowColor:0x000000, shadowAlpha:0.15, drawAll:false};                        
			isoScene.styleRenderers = [factory];                                                
			isoScene.render();
			//设置视角   
			isoView = new IsoView();                        
			isoView.setSize(BFont.stageWidth, BFont.stageHeight);
			setViewCenter(new Pt(SectionConfig.viewCenterX[0], SectionConfig.viewCenterY[0], 0));
			isoView.addScene(isoScene);
			isoView.currentZoom = HomeScene.getInstance().zoom;
			addChild(isoView);
			
			initSectionLocks();
			this.addEventListener(MouseEvent.CLICK, onMouseClick);
			this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
		}
		
		private function onAddedToStage(event:Event):void
		{
			this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			stage.addEventListener(Event.FULLSCREEN, onFullScreen, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.REFRESH, onRefresh, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.ADD_BUILDING, onAddBuilding, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.REMOVE_BUILDING, onRemoveBuilding, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.REFRESH_BUILDING, onRefreshBuilding, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.ATTACK_AREA, onAttackArea, false, 0, true);
			owner.townModel.addEventListener(ModelEvent.ATTACK_BUILDING, onAttackBuilding, false, 0, true);
			owner.addEventListener(ModelEvent.REFRESH, onSectionLockRefresh, false, 0, true);
			onFullScreen(null);
		}
		
		private function onRemovedFromStage(event:Event):void
		{
			this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
			stage.removeEventListener(Event.FULLSCREEN, onFullScreen);
			owner.townModel.removeEventListener(ModelEvent.REFRESH, onRefresh);
			owner.townModel.removeEventListener(ModelEvent.ADD_BUILDING, onAddBuilding);
			owner.townModel.removeEventListener(ModelEvent.REMOVE_BUILDING, onRemoveBuilding);
			owner.townModel.removeEventListener(ModelEvent.REFRESH_BUILDING, onRefreshBuilding);
			owner.townModel.removeEventListener(ModelEvent.ATTACK_AREA, onAttackArea);
			owner.townModel.removeEventListener(ModelEvent.ATTACK_BUILDING, onAttackBuilding);
			owner.removeEventListener(ModelEvent.REFRESH, onSectionLockRefresh);
		}
		
		/**
		 * 更新所有建筑
		 * */
		private function onRefresh(event:ModelEvent):void
		{
			clearBuildings();
			var buildings:Object = owner.townModel.buildings;
			for (var i:String in buildings)
			{
				var buildingModel:BuildingModel = buildings[i];
				var buildingGrid:BuildingGrid = B3Factory.createBuildingGrid(buildingModel);
				buildingGrid.moveTo(buildingModel.posX * gridWidth, buildingModel.posY * gridWidth, 0.1);
				isoScene.addChild(buildingGrid);
			}
		}
		
		/**
		 * 增加建筑
		 * */
		private function onAddBuilding(event:ModelEvent):void
		{
			//移除重叠建筑
			var removeIds:Array = event.data["removeIds"];
			if (removeIds != null)
			{
				for (var i:int = 0; i < removeIds.length; i++)
				{
					removeBuildingById(removeIds[i]);
				}
			}
			var buildingId:int = event.data["buildingInfo"]["id"];
			var buildingModel:BuildingModel = owner.townModel.buildings[buildingId];
			var buildingGrid:BuildingGrid = B3Factory.createBuildingGrid(buildingModel);
			buildingGrid.moveTo(buildingModel.posX * gridWidth, buildingModel.posY * gridWidth, 0.1);
			TweenLite.from(buildingGrid, 0.1, {z: 15});
			isoScene.addChild(buildingGrid);
			BSound.getInstance().playEffect("SoundTowerPlacement");
			finishBuild();
		}
		
		/**
		 * 移除建筑
		 * */
		private function onRemoveBuilding(event:ModelEvent):void
		{
			var buildingId:int = event.data["buildingInfo"]["id"];
			removeBuildingById(buildingId);
		}
		
		/**
		 * 刷新建筑
		 * */
		private function onRefreshBuilding(event:ModelEvent):void
		{
			var buildingId:int = event.data["buildingInfo"]["id"];
			var targetBuilding:BuildingGrid = getBuildingById(buildingId);
			if (targetBuilding != null)
				targetBuilding.onRefresh(event);
		}
		
		/**
		 * 刷新建筑范围
		 */
		private function onAttackArea(event:ModelEvent):void
		{
			var data:Object = event.data;
			if (data['err'] == 0)
			{
				var targetBuildingId:int = data['targetBuildingId'];
				var objectIndex:int = data['objectIndex'];
				var targetBuilding:BuildingGrid = getBuildingById(targetBuildingId);
				if (targetBuilding != null)
				{
					switch (objectIndex)
					{
						case CardConfig.ROCKET_BOMB:
							playRocketBomb(targetBuilding);
						break;
						case CardConfig.NUCLEAR_BOMB:
							playNuclearBomb(targetBuilding);
						break;
					}
				}
			}
		}
		
		/**
		 * 攻击效果
		 */
		private function onAttackBuilding(event:ModelEvent):void
		{
			var data:Object = event.data;
			if (data['err'] == 0)
			{
				//获得目标建筑的实例
				var targetBuildingId:int = data['targetBuildingId'];
				var rocketBuildingIndex:int = data['rocketBuildingIndex'];
				var rocketRoofType:int = data['rocketRoofType'];
				var targetBuilding:BuildingGrid = getBuildingById(targetBuildingId);
				if (targetBuilding != null)
				{
					targetBuilding.onRefresh(event);
					//表现攻击动画
					playRocketAttack(targetBuilding, rocketBuildingIndex, rocketRoofType);
				}
			}
			else
			{	
				var popMessage:PopMessage;
				if (data["err"] == 101)
				{
					popMessage = new PopMessage("此楼已是断壁残垣", 0xFF0000);
				}
				else if (data["err"] == 102)
				{
					popMessage = new PopMessage("今天已经攻击过这栋楼", 0xFF0000);
				}
				else if (data["err"] == 104)
				{
					popMessage = new PopMessage("今儿攻击他不少次，明儿再来", 0xFF0000);
				}
				else
				{
					popMessage = new PopMessage("其他错误:", data["err"]);
				}
				WidgetManager.getInstance().popOut([popMessage]);
			}
		}
		
		//初始化街区锁
		private function initSectionLocks():void
		{
			lockGrids.setSize(gridWidth, gridWidth, 0.2);
			for (var i:int = Config.townConfigs[0].sectionConfigs.length - 1; i >= 0; i--)
			{
				var sectionConfig:SectionConfig = Config.townConfigs[0].sectionConfigs[i];
				if (owner.historyMaxPopulation < sectionConfig.requirePopulation)
				{
					var BlockShadow:Class = ResourceHelper.getInstance().getClassByName("BlockShadow");
					var globalPointX:int = sectionConfig.globalPoint[0];
					var globalPointY:int = sectionConfig.globalPoint[1];
					var pts:Array = sectionConfig.sectionPoints;
					for (var j:int = 0; j < pts.length; j++)
					{
						var pt:Point = pts[j];
						var dark:LockGrid = new LockGrid(i);
						dark.setSize(gridWidth, gridWidth, gridWidth);
						dark.sprites = [BlockShadow];
						dark.moveTo(pt.x * gridWidth, pt.y * gridWidth, 0.2);
						lockGrids.addChild(dark);
					}
				}
				else
				{
					currentSection = i;
					break;
				}
			}
		}

		//街区锁更新
		private function onSectionLockRefresh(event:ModelEvent):void
		{
			var townConfig:TownConfig = Config.townConfigs[0];
			while (currentSection + 1 < townConfig.sectionConfigs.length)
			{
				var nextSectionConfig:SectionConfig = townConfig.sectionConfigs[currentSection + 1];
				if (owner.historyMaxPopulation >= nextSectionConfig.requirePopulation)
				{
					currentSection++;
					//自己且不是首次加载
					if (owner.userId == PlayerManager.getInstance().myUserId)
					{
						var unlockSectionMovie:UnlockSectionMovie = new UnlockSectionMovie(currentSection);
						WidgetManager.getInstance().popOutOneByOne(unlockSectionMovie);
					}
					else
					{
						removeLocks(currentSection);
					}
				}
				else
				{
					break;
				}
			}
		}
		
		//移除街区锁
		public function removeLocks(sectionIndex:int):void
		{
			var unlockSections:Object = new Object();
			for (var i:int = 0, len:int = lockGrids.children.length; i < len; i++)
			{
				var lockGrid:LockGrid = lockGrids.children[i];
				if (lockGrid.sectionIndex == sectionIndex)
				{
					lockGrids.removeChild(lockGrid);
					len--;
					i--;
				}	
			}
		}
		
		/**
		 * 按ID移除建筑
		 * */
		private function removeBuildingById(buildingId:int):void
		{
			for (var i:int = 0,len:int = isoScene.children.length; i<len; i++)
			{
				if (isoScene.children[i] is BuildingGrid)
				{
					var buildingGrid:BuildingGrid = isoScene.children[i];
					if (buildingGrid.buildingModel.id == buildingId)
					{
						isoScene.removeChild(buildingGrid);
						buildingGrid.destroy();
						break;
					}
				}
			}
		}
		
		public function getBuildingByPos(x:int, y:int):BuildingGrid
		{
			for (var i:int = 0,len:int = isoScene.children.length; i < len; i++)
			{
				if (isoScene.children[i] is BuildingGrid)
				{
					var buildingGrid:BuildingGrid = isoScene.children[i];  
					if (buildingGrid.buildingModel.id != 0 )
					{
						var pts:Array = buildingGrid.buildingModel.getPts();
						for	(var j:int =0;j < pts.length;j++)
						{
							if ((pts[j] as Point).x == x && (pts[j] as Point).y == y)
								return buildingGrid;
						}
					}
				}
			}
			return null;
		}
		
		//清除所有建筑
		public function clearBuildings():void
		{
			for (var i:int = 0,len:int = isoScene.children.length; i<len; i++)
			{
				if (isoScene.children[i] is BuildingGrid)
				{
					var buildingGrid:BuildingGrid = isoScene.children[i]; 
					isoScene.removeChild(buildingGrid);
					buildingGrid.destroy();
					i--;
					len--;
				}
			}
		}
		
		public function addHighLight(buildingIndex:int):void
		{
			if (highlight.parent == null)
			{
				var availablePoints:Array = owner.townModel.getAvailablePoints(buildingIndex);
				isoScene.addChild(highlight);
				highlight.setHighlight(availablePoints, 0x00FF00);
				for (var i:int = 0,len:int = isoScene.children.length; i<len; i++)
				{
					if (isoScene.children[i] is BuildingGrid)
					{
						var buildingGrid:BuildingGrid = isoScene.children[i];
						buildingGrid.container.alpha = 0.5; 
					}
				}
			}
		}
		
		public function removeHighLight():void
		{
			isoScene.removeChild(highlight);
			for (var i:int = 0,len:int = isoScene.children.length; i<len; i++)
			{
				if (isoScene.children[i] is BuildingGrid)
				{
					var buildingGrid:BuildingGrid = isoScene.children[i];
					buildingGrid.container.alpha = 1; 
				}
			}
		}
		
		private function onFullScreen(event:Event):void
		{
			isoView.setSize(BFont.stageWidth, BFont.stageHeight);
		}
		
		public function zoomIn(delta:Number):void
		{
			var home:HomeScene = HomeScene.getInstance();
			home.zoom = Math.min(home.zoom + delta, 1.3);
		}
		
		public function zoomOut(delta:Number):void
		{
			var home:HomeScene = HomeScene.getInstance();
			home.zoom = Math.max(home.zoom - delta, 0.5);
		}
		
		public function playMovieAtPos(MovieName:String, fps:Number, x:Number, y:Number, z:Number, 
			onCompleteFunction:Function = null, onCompleteParams:Array = null):void
		{
			var WeaponAttack:Class = ResourceHelper.getInstance().getClassByName(MovieName);
			var weaponAttack0:BasicMc = new BasicMc(WeaponAttack, fps, false, true);
			var movieSprite:IsoSprite = new IsoSprite();
            movieSprite.sprites = [weaponAttack0];
			movieSprite.setSize(Town.gridWidth, Town.gridWidth, Town.gridWidth);
			movieSprite.moveTo(x, y, z);
            movieSprite.container.mouseChildren = false;
            weaponAttack0.setOnCompleteFunction(onCompleteFunction, onCompleteParams);
			isoScene.addChild(movieSprite);
		}
		
		/**
		 * 通过ID获取建筑本身
		 */
		public function getBuildingById(id:int):BuildingGrid
		{
			for (var i:int = 0,len:int = isoScene.children.length; i<len; i++)
			{
				if (isoScene.children[i] is BuildingGrid)
				{
					var buildingGrid:BuildingGrid = isoScene.children[i];
					if (buildingGrid.buildingModel.id == id)
					{
						return buildingGrid; 
					}
				}
			}
			return null;
		}
		
		//播放原子弹攻击
		public function playNuclearBomb(targetBuilding:BuildingGrid):void
		{
			//让原子弹飞
			var RocketImg:Class = ResourceHelper.getInstance().getClassByName("NuclearBomb");
			var rocketImg:Sprite = new RocketImg();
			rocketImg.scaleY = -1;
			rocketImg.x = -rocketImg.width / 2;
			var movieSprite:IsoSprite = new IsoSprite();
            movieSprite.sprites = [rocketImg];
			movieSprite.setSize(Town.gridWidth, Town.gridWidth, Town.gridWidth);
			movieSprite.moveTo(targetBuilding.x + Town.gridWidth, targetBuilding.y + Town.gridWidth, targetBuilding.z + 280);
            movieSprite.container.mouseChildren = false;
            isoScene.addChild(movieSprite);
            TweenLite.to(movieSprite, 0.5, {z: targetBuilding.z, onComplete: isoScene.removeChild, onCompleteParams: [movieSprite]});
			//播放爆炸
			playMovieAtPos("Explode1", 20, targetBuilding.x + Town.gridWidth * 100, targetBuilding.y + Town.gridWidth * 100, targetBuilding.z + Town.gridWidth * 100);
		}
		
		//播放飞弹攻击
		public function playRocketBomb(targetBuilding:BuildingGrid):void
		{
			//让飞弹飞
			var RocketImg:Class = ResourceHelper.getInstance().getClassByName("RocketBomb");
			var rocketImg:Sprite = new RocketImg();
			rocketImg.scaleY = -1;
			rocketImg.x = -rocketImg.width / 2;
			var movieSprite:IsoSprite = new IsoSprite();
            movieSprite.sprites = [rocketImg];
			movieSprite.setSize(Town.gridWidth, Town.gridWidth, Town.gridWidth);
			movieSprite.moveTo(targetBuilding.x + Town.gridWidth, targetBuilding.y + Town.gridWidth, targetBuilding.z + 280);
            movieSprite.container.mouseChildren = false;
            isoScene.addChild(movieSprite);
            TweenLite.to(movieSprite, 0.5, {z: targetBuilding.z, onComplete: isoScene.removeChild, onCompleteParams: [movieSprite]});
			//播放爆炸
			playMovieAtPos("Explode1", 20, targetBuilding.x + Town.gridWidth * 100, targetBuilding.y + Town.gridWidth * 100, targetBuilding.z + Town.gridWidth * 100);
		}
		
		//播放导弹攻击
		public function playRocketAttack(targetBuilding:BuildingGrid, rocketBuildingIndex:int, rocketRoofType:int):void
		{
			//让导弹飞
			var rocketConfig:BuildingConfig = Config.buildingConfigs[rocketBuildingIndex];
			var RocketImg:Class = ResourceHelper.getInstance().getClassByName(rocketConfig.iconImage[rocketRoofType]);
			var rocketImg:Sprite = new RocketImg();
			rocketImg.scaleY = -1;
			rocketImg.x = -rocketImg.width / 2;
			var movieSprite:IsoSprite = new IsoSprite();
            movieSprite.sprites = [rocketImg];
			movieSprite.setSize(Town.gridWidth, Town.gridWidth, Town.gridWidth);
			movieSprite.moveTo(targetBuilding.x + Town.gridWidth, targetBuilding.y + Town.gridWidth, targetBuilding.z + 280);
            movieSprite.container.mouseChildren = false;
            isoScene.addChild(movieSprite);
            TweenLite.to(movieSprite, 0.5, {z: targetBuilding.z, onComplete: isoScene.removeChild, onCompleteParams: [movieSprite]});
			//播放爆炸
			playMovieAtPos("Explode0", 20, targetBuilding.x + Town.gridWidth * 100, targetBuilding.y + Town.gridWidth * 100, targetBuilding.z + Town.gridWidth * 100);
		}
		
		public function rebuild(oldBuilidng:BuildingModel, buildingModel:BuildingModel):void
		{
			var messageBox:MessageBox;
			//协助
			if (PlayerManager.getInstance().myUserId != buildingModel.ownerId)
			{
				if (buildingModel.population > oldBuilidng.population)
				{
					messageBox = new MessageBox("原人口: " + oldBuilidng.population + "，新人口: " + buildingModel.population + "。<br>是否覆盖？", true);
					messageBox.x = -messageBox.width / 2;
					messageBox.y = -messageBox.height / 2;
					messageBox.setOKCall(owner.townModel.rebuild, [buildingModel, true]);
					WidgetManager.getInstance().popOut([messageBox], true);
				}
				else
				{
					var popMessage:PopMessage = new PopMessage("未能超过原有建筑人口！", 0xFF0000);
					WidgetManager.getInstance().popOut([popMessage]);
				}
			}
			else if (PlayerManager.getInstance().myUserId == buildingModel.ownerId)
			{
				messageBox = new MessageBox("原人口: " + oldBuilidng.population + "，新人口: " + buildingModel.population + "。<br>是否覆盖？", true);
				messageBox.x = -messageBox.width / 2;
				messageBox.y = -messageBox.height / 2;
				messageBox.setOKCall(owner.townModel.rebuild, [buildingModel, true]);
				WidgetManager.getInstance().popOut([messageBox], true);
			}
			finishBuild();
		}
		
		//开始建造
		public function startToBuild(buildingModel:BuildingModel):void
		{
			HomeScene.getInstance().setOperationMode(HomeScene.BUILDINGMODE);
			this.currentBuildingIndex = buildingModel.buildingIndex;
			mouseBuildingGrid = B3Factory.createBuildingGrid(buildingModel);
			mouseBuildingGrid.container.mouseEnabled = false;
			mouseBuildingGrid.container.alpha = 0.8;
			isoScene.addChild(mouseBuildingGrid);
			var buildingConfig:BuildingConfig = Config.buildingConfigs[currentBuildingIndex];
			addHighLight(currentBuildingIndex);
		}
		
		//购买房产时选择放置地点
		public function startToPlace(buildingModel:BuildingModel):void
		{
			var home:HomeScene = HomeScene.getInstance(); 
			PlayerManager.getInstance().me.townModel.removeEventListener( ModelEvent.REFRESH, home.startToPlace);
			home.setOperationMode(HomeScene.FINDPLACEMODE);
			this.currentBuildingIndex = buildingModel.buildingIndex;
			buildingModel.locatedFlag = false;
			mouseBuildingGrid = B3Factory.createBuildingGrid(buildingModel);
			mouseBuildingGrid.container.mouseEnabled = false;
			mouseBuildingGrid.container.alpha = 0.8;
			isoScene.addChild(mouseBuildingGrid);
			var buildingConfig:BuildingConfig = Config.buildingConfigs[currentBuildingIndex];
			addHighLight(currentBuildingIndex);
		}
		
		public function finishBuild():void
		{
			HomeScene.getInstance().setOperationMode(HomeScene.NONEMODE);
			this.currentBuildingIndex = -1;
			if (mouseBuildingGrid != null)
				isoScene.removeChild(mouseBuildingGrid);
			mouseBuildingGrid = null;
			removeHighLight();
		}
		
		private function onMouseMove(evt:MouseEvent):void
		{
			if (mouseDownPos != null && evt.buttonDown)
			{
				const sensitivity:Number = 0.85;
				var diff:Pt = new Pt(evt.stageX - mouseDownPos.x, evt.stageY - mouseDownPos.y);
				setViewCenter(new Pt(mouseDownViewCenter.x - diff.x * sensitivity, mouseDownViewCenter.y - diff.y * sensitivity, mouseDownViewCenter.z));
			}
			if (replaceBuildings != null)
			{
				for (var i:int = 0;i < replaceBuildings.length;i++)
				{
					//被取代建筑物群重新显示
					var replaceBuilding:BuildingGrid = replaceBuildings[i] as BuildingGrid;
					replaceBuilding.container.visible = true;
				}
			}
			if( HomeScene.getInstance().cardItem != null )
			{
				HomeScene.getInstance().cardItem.visible = true;
				HomeScene.getInstance().cardItem.x = evt.stageX;
				HomeScene.getInstance().cardItem.y = evt.stageY;
			}
			
			if (HomeScene.getInstance().getOperationMode() == HomeScene.BUILDINGMODE || HomeScene.getInstance().getOperationMode() == HomeScene.FINDPLACEMODE)
			{
				var pt:Pt = new Pt(isoScene.container.mouseX, isoScene.container.mouseY);
				IsoMath.screenToIso(pt);
				pt.x = int(pt.x / gridWidth);
				pt.y = int(pt.y / gridWidth);
				setMouseBuildingGrid(pt.x, pt.y);
			}
		}
		
		/**
		 * 函数中通过对位置的判断 进而计算出显示提示框的位置
		 * */
		public function setViewCenter(pt:Pt, isIsometrc:Boolean = false):void
		{
			if (isIsometrc)
				currentViewCenter = IsoMath.isoToScreen(pt);
			else
				currentViewCenter = pt;
			isoView.centerOnPt(pt, false);
		}
		
		public function setMouseBuildingGrid(posX:int, posY:int):void
		{
			mouseBuildingGrid.buildingModel.posX = posX;
			mouseBuildingGrid.buildingModel.posY = posY;
			mouseBuildingGrid.moveTo(posX * gridWidth, posY * gridWidth, 0.2);
			addHighLight(currentBuildingIndex);
			
			if (owner.townModel.checkPosAvailable(mouseBuildingGrid.buildingModel))
			{
				//由于建筑物可能是奇迹这一类的东西，因此它所取代的建筑物可能是1到4个 应该使用数组或其他方式储存
				var pts:Array = mouseBuildingGrid.buildingModel.getPts();
				//这里根据鼠标锁携带的建筑物的占据的每个格子来判断是否存在其他建筑物
				replaceBuildings = new Array();
				for (var j:int = 0;j < pts.length;j++)
				{
					var x:int  = (pts[j] as Point).x ;
					var y:int  = (pts[j] as Point).y ;
					var replaceBuilding:BuildingGrid = this.getBuildingByPos(x, y);
					if (replaceBuilding != null)
					{
//						replaceBuilding.container.visible = false;
						replaceBuildings.push(replaceBuilding);
					}
				}	
				mouseBuildingGrid.popCoverMessage(replaceBuildings);
				//这是当他需要覆盖别人时所要发出的提示信息 通过类型来提示建筑物的信息输出
			}
			else
			{
				//关闭多个弹窗
				WidgetManager.getInstance().closeSeveralMessages();
			}
		}
		
		private function onMouseClick(evt:MouseEvent):void
		{
			if (HomeScene.getInstance().getOperationMode() == HomeScene.BUILDINGMODE || HomeScene.getInstance().getOperationMode() == HomeScene.FINDPLACEMODE)
			{
				var popMessage:PopMessage;
				var pt:Pt = new Pt(isoScene.container.mouseX, isoScene.container.mouseY);        
				IsoMath.screenToIso(pt);
				pt.x = int(pt.x / gridWidth);
				pt.y = int(pt.y / gridWidth);
				var buildingModel:BuildingModel = mouseBuildingGrid.buildingModel;
				buildingModel.ownerId = owner.userId;
				buildingModel.posX = pt.x;
				buildingModel.posY = pt.y;
				
				if (PlayerManager.getInstance().myUserId != buildingModel.ownerId)
				{
					//只能在自己家建设
					popMessage = new PopMessage("不能在别人的家里进行建设", 0xFF0000);
					WidgetManager.getInstance().popOut([popMessage]);
				}
				else
				{
					if (owner.townModel.checkPosAvailable(buildingModel))
					{
						//获得街区索引
						var townConfig:TownConfig = Config.townConfigs[0];
						var sectionIndex:int = townConfig.getSectionIndex(buildingModel.posX, buildingModel.posY);
						if (sectionIndex >= 0)
						{
							//放置 建设房屋
							if (HomeScene.getInstance().getOperationMode() == HomeScene.BUILDINGMODE)
							{
								buildingModel.sectionIndex = sectionIndex;
								owner.townModel.addBuilding(buildingModel);
							}
							//放置 购买房屋
							else if(HomeScene.getInstance().getOperationMode() == HomeScene.FINDPLACEMODE)
							{
								buildingModel.sectionIndex = sectionIndex;
								var cardItem:CardItem = HomeScene.getInstance().cardItem; 
								cardItem.cardModel.useBuyBuildingCard(buildingModel);
							}
						}
						else
						{
							popMessage = new PopMessage("不能在此处摆放", 0xFF0000);
							WidgetManager.getInstance().popOut([popMessage]);
						}
					}
					else
					{
						popMessage = new PopMessage("不能在此处摆放", 0xFF0000);
						WidgetManager.getInstance().popOut([popMessage]);
					}
				}
			}
		}
		
		private function onMouseDown(evt:MouseEvent):void
		{
			if (mouseDownPos == null)
			{
				mouseDownPos = new Pt(evt.stageX, evt.stageY);
				mouseDownViewCenter = currentViewCenter;
			}
		}
		
		private function onMouseUp(evt:MouseEvent):void
		{
			mouseDownPos = null;
			BottomPane.getInstance().hide();
		}
		
		private function completeCallback():void
		{        
			this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
				
		private function enterFrameHandler(evt:Event):void
		{        
			isoScene.render();
		}
		
		public function destroy():void
		{
			clearBuildings();
			this.removeEventListener(MouseEvent.CLICK, onMouseClick);
			this.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			this.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			this.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			this.owner = null;
		}
				
	}
}